import { DirectiveOptions } from 'vue'
import { InputNumber } from 'element-ui'

interface ElInputNumber extends InputNumber {
  currentValue: number
  _onblur?: () => void
}

/**
 * 指令：`v-input-number-fix`，修复 `ElInputNumber` 控件
 * @description
 * 1. 避免必填数字值清除为 `undefined`，使用最小值或 `0` 代替
 * 2. 避免 `v-model` 为 Computed 值时，清除后无法展示默认值
 */
const inputNumberFix: DirectiveOptions = {
  bind(el, binding) {
    const vm: undefined | ElInputNumber = (el as any).__vue__

    if (vm) {
      const onblur = () => {
        if (vm.currentValue !== vm.value) {
          vm.currentValue = vm.value
        }

        if (!vm.currentValue && vm.currentValue !== 0) {
          vm.currentValue = vm.min || 0
        }
      }

      vm._onblur = onblur
      vm.$on('blur', onblur)
    }
  },

  unbind(el) {
    const vm: undefined | ElInputNumber = (el as any).__vue__

    if (vm?._onblur) {
      vm.$off('blur', vm._onblur)
    }
  }
}

export default inputNumberFix
